<template>
  <view class="container">
    <scroll-view scroll-y class="detail-scroll">
      <!-- 资源图片 -->
      <swiper class="resource-swiper" circular indicator-dots autoplay interval="3000" duration="500">
        <swiper-item v-for="(item, index) in resourceDetail.images || []" :key="index">
          <image class="swiper-image" :src="item" mode="aspectFit"></image>
        </swiper-item>
      </swiper>

      <!-- 资源信息 -->
      <view class="resource-info">
        <view class="resource-title">{{ resourceDetail.name }}</view>
        <view class="resource-price" v-if="resourceDetail.rental_price">¥{{ resourceDetail.rental_price }}元/{{ resourceDetail.unit || '件' }}</view>
        <view class="resource-meta">
          <view class="meta-item">
            <text class="meta-label">编码：</text>
            <text class="meta-value">{{ resourceDetail.code || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">名称：</text>
            <text class="meta-value">{{ resourceDetail.name }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">使用状态：</text>
            <text class="meta-value">
              {{ getStatusText(resourceDetail.status) }}
            </text>
          </view>
          <view class="meta-item">
            <text class="meta-label">分类：</text>
            <text class="meta-value">{{ resourceDetail.category_name || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">数量：</text>
            <text class="meta-value">{{ transfer.quantity || '0' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">总价：</text>
            <text class="meta-value">{{ transfer.transfer_price || '0' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">发布日期：</text>
            <text class="meta-value">{{ resourceDetail.create_time || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">规格型号：</text>
            <text class="meta-value">{{ resourceDetail.specification || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">技术状况：</text>
            <text class="meta-value">{{ resourceDetail.condition || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">备注：</text>
            <text class="meta-value">{{ resourceDetail.remark || '暂无' }}</text>
          </view>
        </view>
      </view>

      <!-- 资源描述 -->
<!--      <view class="resource-section">-->
<!--        <view class="section-title">图片</view>-->
<!--        <view class="resource-images">-->
<!--          <image -->
<!--            v-for="(item, index) in resourceDetail.images || []" -->
<!--            :key="index" -->
<!--            :src="item" -->
<!--            mode="widthFix" -->
<!--            class="resource-image"-->
<!--            @click="previewImage(item, resourceDetail.images)"-->
<!--          ></image>-->
<!--        </view>-->
<!--      </view>-->

      <!-- 联系信息 -->
      <view class="resource-section">
        <view class="section-title">单位信息</view>
        <view class="section-content">
          <view class="meta-item">
            <text class="meta-label">所属单位：</text>
            <text class="meta-value">{{ resourceDetail.project_name || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">单位原值：</text>
            <text class="meta-value">{{ resourceDetail.unit_price || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">总原值：</text>
            <text class="meta-value">{{ resourceDetail.total_price || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">详细地址：</text>
            <text class="meta-value">{{ resourceDetail.address || '暂无' }}</text>
          </view>
        </view>
      </view>
      <view class="resource-section">
        <view class="section-title">审批信息</view>
        <view class="section-content">
          <view class="meta-item">
            <text class="meta-label">申请人：</text>
            <text class="meta-value">{{ transfer.apply_user_name || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">审批人：</text>
            <text class="meta-value">{{ resourceDetail.approve_user_name || '暂无' }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">实际审批人：</text>
            <text class="meta-value">{{ resourceDetail.approved_user_name || '暂无' }}</text>
          </view>
        </view>
      </view>

      <!-- 相似资源 -->
<!--      <view class="resource-section">-->
<!--        <view class="section-title">相似资源</view>-->
<!--        <scroll-view scroll-x class="similar-scroll">-->
<!--          <view class="similar-item" v-for="(item, index) in similarResources" :key="index" @click="goToDetail(item.id)">-->
<!--            <image class="similar-image" :src="item.image" mode="aspectFill"></image>-->
<!--            <view class="similar-name">{{ item.name }}</view>-->
<!--            <view class="similar-status" :class="getStatusClass(item.status)">-->
<!--              {{ getStatusText(item.status) }}-->
<!--            </view>-->
<!--          </view>-->
<!--        </scroll-view>-->
<!--      </view>-->
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="action-left">
        <button class="action-btn share-btn" open-type="share">
          <u-icon name="share" size="40" color="#666"></u-icon>
          <text>分享</text>
        </button>
<!--        <view class="action-btn" @click="toggleFavorite">-->
<!--          <u-icon :name="isFavorite ? 'star-fill' : 'star'" size="40" :color="isFavorite ? '#FF9500' : '#666'"></u-icon>-->
<!--          <text>收藏</text>-->
<!--        </view>-->
      </view>
      <view class="action-right">
        <button
            v-if="transfer.status === 'pending'"
            class="primary-btn error-btn"
            @click="handleCancel"
        >
         取消申请
        </button>
      </view>
    </view>

    <!-- 申请使用弹窗 -->
    <u-popup height="70vh" v-model="showApplyPopup" mode="bottom" @close="closeApplyPopup" border-radius="24" closeable>
      <view class="apply-popup">
        <view class="popup-title">申请使用</view>
        <view class="form-item">
          <view class="form-label">使用时间</view>
          <view class="form-input date-picker" @click="showDatePicker = true">
            <text>{{ applyForm.startDate || '请选择开始日期' }}</text>
            <u-icon name="arrow-right" size="28" color="#999"></u-icon>
          </view>
        </view>
        <view class="form-item">
          <view class="form-label">归还时间</view>
          <view class="form-input date-picker" @click="showEndDatePicker = true">
            <text>{{ applyForm.endDate || '请选择结束日期' }}</text>
            <u-icon name="arrow-right" size="28" color="#999"></u-icon>
          </view>
        </view>
        <view class="form-item">
          <view class="form-label">数量</view>
          <input class="form-input" type="number" :max="resourceDetail.quantity" v-model="applyForm.quantity" placeholder="数量"/>
        </view>
        <view class="form-item">
          <view class="form-label">备注</view>
          <textarea class="form-textarea" v-model="applyForm.remark" placeholder="说明"/>
        </view>
        <view class="popup-buttons">
          <button class="cancel-btn" @click="closeApplyPopup">取消</button>
          <button class="confirm-btn" @click="submitApply">确认申请</button>
        </view>
      </view>
    </u-popup>

    <!-- 日期选择器 -->
    <u-calendar
      v-model="showDatePicker"
      @change="confirmStartDate"
      @close="showDatePicker = false"
      mode="date"
      :min-date="minDate"
      :max-date="maxDate"
    ></u-calendar>

    <u-calendar
      v-model="showEndDatePicker"
      @change="confirmEndDate"
      @close="showEndDatePicker = false"
      mode="date"
      :max-date="maxDate"
      :min-date="applyForm.startDate || minDate"
    ></u-calendar>
  </view>
</template>

<script>
import dayjs from 'dayjs';
import { mapGetters } from 'vuex'
export default {
  name: "ResourceDetail",
  computed: {
    ...mapGetters(['userInfo'])
  },
  data() {
    return {
      resourceId: null,
      resourceDetail: {},
      similarResources: [],
      isFavorite: false,
      showApplyPopup: false,
      showDatePicker: false,
      showEndDatePicker: false,
      minDate: dayjs().format('YYYY-MM-DD'),
      maxDate: '2099-01-01',
      applyForm: {
        startDate: '',
        endDate: '',
        remark: ''
      },
      transfer_id: '',
      transfer: {}
    };
  },
  onLoad(options) {
    if (options.id) {
      this.resourceId = options.id;
    }
    if (options.transfer_id) {
      this.transfer_id = options.transfer_id;
    }
  },
  onShow() {
    if (this.resourceId) {
      this.getResourceDetail();
    }
    if (this.transfer_id) {
      this.$api.getMyApplyDetail({
        id: this.transfer_id
      }).then(res => {
        this.transfer = res
      })
    }
  },
  methods: {
    handleCancel() {
      let that = this
      uni.showModal({
        title: '提示',
        content: '确认取消申请吗？',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: function () {
          uni.showLoading({
            title: '加载中...'
          });
          that.$api.cancelMyApplies({
            id: that.transfer_id
          }).then(res => {
            uni.showToast({
              title: '操作成功',
              icon: 'none'
            });
            setTimeout(() => {
              uni.hideLoading();
              // 返回列表页
              uni.navigateBack();
            }, 1000);
          })
        }
      })
    },
    // 获取资源详情
    async getResourceDetail() {
      try {
        uni.showLoading({
          title: '加载中...'
        });

        const res = await this.$api.getResourceDetail({ id: this.resourceId });
        this.resourceDetail = {
          ...res,
          images: res.images ? res.images.split(',') : []
        };

        uni.hideLoading();
      } catch (e) {
        console.log(e);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
        uni.hideLoading();
      }
    },

    // 更新浏览次数
    updateViewCount() {
      // 实际项目中应该调用API更新浏览次数
      // this.$api.updateResourceViewCount({ id: this.resourceId });
    },

    // 预览图片
    previewImage(current, urls) {
      uni.previewImage({
        current: current,
        urls: urls
      });
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'available':
          return '闲置';
          break
        default:
          return '使用中';
      }
    },

    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case 1:
          return 'status-available';
        case 2:
          return 'status-using';
        case 3:
          return 'status-reserved';
        default:
          return '';
      }
    },

    // 切换收藏状态
    toggleFavorite() {
      this.isFavorite = !this.isFavorite;
      uni.showToast({
        title: this.isFavorite ? '已收藏' : '已取消收藏',
        icon: 'none'
      });
    },

    // 跳转到其他资源详情
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/resource/detail?id=${id}`
      });
    },

    // 处理申请使用
    handleApply() {
      if (!this.userInfo.id) {
        uni.showModal({
          title: '登录提示',
          content: '您暂未登录，是否登录？',
          showCancel: true,
          cancelText: '取消',
          confirmText: '确定',
          success: function (res) {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            } else if (res.cancel) {
              console.log('用户点击了取消');
            }
          },
          fail: function (err) {
            console.log('调用失败', err);
          },
          complete: function () {
            console.log('调用结束');
          }
        });
        return;
      }

      this.showApplyPopup = true;
    },
    editItem() {
      uni.navigateTo({
        url: `/pages/resource/edit?id=${this.resourceDetail.id}`
      });
    },
    handleUpdatePublic() {
      uni.showLoading()
      this.$api.updateIdleItemStatus({
        id: this.resourceDetail.id
      }).then(res => {
        uni.showToast({
          title: '操作成功'
        })
        setTimeout(() => {
          this.getResourceDetail()
        },1000)
      }).finally(() => {

      })
    },

    // 关闭申请弹窗
    closeApplyPopup() {
      this.showApplyPopup = false;
    },

    // 确认开始日期
    confirmStartDate(e) {
      console.log(e)
      this.applyForm.startDate = e.result;
      this.applyForm.endDate = ''
      this.showDatePicker = false;
    },

    // 确认结束日期
    confirmEndDate(e) {
      this.applyForm.endDate = e.result;
      this.showEndDatePicker = false;
    },

    // 提交申请
    submitApply() {
      if (!this.applyForm.startDate) {
        uni.showToast({
          title: '请选择使用时间',
          icon: 'none'
        });
        return;
      }

      if (!this.applyForm.endDate) {
        uni.showToast({
          title: '请选择归还时间',
          icon: 'none'
        });
        return;
      }
      if (!this.applyForm.quantity) {
        uni.showToast({
          title: '请填写数量',
          icon: 'none'
        });
        return;
      }
      if (Number(this.applyForm.quantity) > Number(this.resourceDetail.quantity)) {
        uni.showToast({
          title: '数量不能大于总数量',
          icon: 'none'
        });
        return;
      }

      // 模拟API调用，实际项目中应该替换为真实API
      const params = {
        item_id: this.resourceId,
        start_date: this.applyForm.startDate,
        end_date: this.applyForm.endDate,
        apply_user_id: this.userInfo.id,
        apply_user_name: this.userInfo.nickname,
        remark: this.applyForm.remark,
        create_user_id: this.resourceDetail.create_user_id,
        create_user_name: this.resourceDetail.create_user_name,
      };
      // 模拟成功响应
      uni.showLoading({
        title: '提交中...'
      });

      this.$api.applyResource(params).then(res => {
        this.getResourceDetail()
        // 处理成功响应
        setTimeout(() => {
          uni.hideLoading();
          uni.showToast({
            title: '申请成功',
            icon: 'success'
          });
          this.closeApplyPopup();
        }, 1000);
      }).catch(err => {
        // 处理错误
      });

    }
  },
  // 分享
  onShareAppMessage() {
    return {
      title: this.resourceDetail.name || '闲置资源详情',
      path: `/pages/resource/detail?id=${this.resourceId}`
    };
  }
};
</script>

<style lang="scss">
page {
  height: 100%;
  overflow: auto;
}
.container {
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

.detail-scroll {
  flex: 1;
  overflow: hidden;
}

.resource-swiper {
  height: 500rpx;

  .swiper-image {
    width: 100%;
    height: 100%;
  }
}

.resource-info {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .resource-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .resource-price {
    font-size: 40rpx;
    font-weight: bold;
    color: #FF5A5F;
    margin-bottom: 20rpx;
  }

  .resource-meta {
    .meta-item {
      display: flex;
      margin-bottom: 16rpx;
      font-size: 28rpx;

      .meta-label {
        color: #999;
        width: 200rpx;
      }

      .meta-value {
        color: #333;
        flex: 1;
      }
    }
  }
}

.resource-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    position: relative;
    padding-left: 20rpx;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 30rpx;
      background-color: #1A8DFF;
      border-radius: 3rpx;
    }
  }

  .section-content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

.resource-images {
  display: flex;
  flex-wrap: wrap;

  .resource-image {
    width: 100%;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
  }
}

.record-list {
  .record-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    &:last-child {
      border-bottom: none;
    }

    .record-user {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 30rpx;

      .user-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-bottom: 10rpx;
      }

      .user-name {
        font-size: 24rpx;
        color: #333;
      }
    }

    .record-info {
      flex: 1;

      .record-time {
        font-size: 26rpx;
        color: #333;
        margin-bottom: 10rpx;
      }

      .record-purpose {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.similar-scroll {
  white-space: nowrap;

  .similar-item {
    display: inline-block;
    width: 240rpx;
    margin-right: 20rpx;
    position: relative;

    .similar-image {
      width: 240rpx;
      height: 240rpx;
      border-radius: 12rpx;
    }

    .similar-name {
      font-size: 26rpx;
      color: #333;
      margin-top: 10rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .similar-status {
      position: absolute;
      top: 10rpx;
      left: 10rpx;
      padding: 4rpx 12rpx;
      border-radius: 6rpx;
      font-size: 22rpx;

      &.status-available {
        background-color: #1A8DFF;
        color: #fff;
      }

      &.status-using {
        background-color: #FF9500;
        color: #fff;
      }

      &.status-reserved {
        background-color: #FF3B30;
        color: #fff;
      }
    }
  }
}

.action-bar {
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16rpx;
  border-top: 1rpx solid #eee;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
  .action-left {
    display: flex;

    .action-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 40rpx;

      text {
        font-size: 22rpx;
        color: #666;
        margin-top: 6rpx;
      }
    }

    .share-btn {
      background-color: transparent;
      padding: 0;
      margin: 0;
      line-height: normal;
      border: none;
      margin:0 12rpx;

      &::after {
        border: none;
      }
    }
  }

  .action-right {
    flex-grow: 1;
    display: flex;
    justify-content: flex-end;

    .primary-btn {
      width: 550rpx;
      background-color: #1A8DFF;
      color: #fff;
      font-size: 28rpx;
      padding: 0 40rpx;
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 35rpx;
      margin: 0 20rpx;

      &[disabled] {
        background-color: #ccc;
        color: #fff;
      }
    }
    .error-btn {
      background-color: #FF5A5F;
    }
  }
}

.apply-popup {
  padding: 30rpx;

  .popup-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .form-item {
    margin-bottom: 20rpx;

    .form-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
    }

    .form-input {
      height: 80rpx;
      background-color: #f5f5f5;
      border-radius: 8rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;

      &.date-picker {
        justify-content: space-between;
      }
    }

    .form-textarea {
      height: 200rpx;
      background-color: #f5f5f5;
      border-radius: 8rpx;
      padding: 20rpx;
      font-size: 28rpx;
      width: 100%;
    }
  }

  .popup-buttons {
    display: flex;
    margin-top: 40rpx;

    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 28rpx;
      border-radius: 8rpx;
    }

    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;
      margin-right: 20rpx;
    }

    .confirm-btn {
      background-color: #1A8DFF;
      color: #fff;
    }
  }
}
</style>
